package com.qiyee.dalligent.common.utils;

/**
 * Title: CustomCellWriteHandler
 * Description:
 *
 * @author xt.ahs.shiyaning1
 * @version 1.0.0
 * @Date 2025/1/8 09:53
 */
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.collect.Maps;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;

public class CustomCellWriteHandler implements CellWriteHandler, SheetWriteHandler  {





    @Override
    public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
        Head head, Integer integer, Integer integer1, Boolean aBoolean) {
        System.out.println("--beforeCellCreate--");

    }

    @Override
    public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell,
        Head head, Integer integer, Boolean aBoolean) {
        System.out.println("--afterCellCreate--");

    }

    @Override
    public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
        CellData cellData, Cell cell, Head head, Integer relativeRowIndex, Boolean aBoolean) {
        System.out.println("--afterCellDataConverted--");
        int columnIndex1 = cell.getColumnIndex();
        if (cellData==null){
            return;
        }

        // 如果是我们想要修改的单元格，则进行内容修改
        if ( columnIndex1 == 1) {
            System.out.println("relativeRowIndex:"+relativeRowIndex+"--columnIndex--,"+columnIndex1+",cell"+cell+",data:"+cellData);
            cell.setCellValue("");

            byte[] pngData = generateBarcodeByteArray(cellData.toString());
            cell.setBlank();
            Drawing drawing = writeSheetHolder.getSheet().createDrawingPatriarch();
            /*
             * 参数定义： 第一个参数是（x轴的开始节点）； 第二个参数是（是y轴的开始节点）； 第三个参数是（是x轴的结束节点）；
             * 第四个参数是（是y轴的结束节点）； 第五个参数是（是从Excel的第几列开始插入图片，从0开始计数）；
             * 第六个参数是（是从excel的第几行开始插入图片，从0开始计数）； 第七个参数是（图片宽度，共多少列）；
             * 第8个参数是（图片高度，共多少行）；
             */
            ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, columnIndex1 , relativeRowIndex+1,  columnIndex1+1, relativeRowIndex+2);
            //anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);
            Picture picture =
                drawing.createPicture(anchor, writeSheetHolder.getParentWriteWorkbookHolder().getWorkbook().addPicture(pngData,
                    Workbook.PICTURE_TYPE_PNG));
           // picture.resize();
            // 修改单元格的值

        }
    }

    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
        List<CellData> list, Cell cell, Head head, Integer relativeRowIndex, Boolean aBoolean) {
        System.out.println("--afterCellDispose--");


    }
    public static byte[] generateBarcodeByteArray(String content)  {
        try {
            if (StringUtils.isBlank(content)){
                return null;
            }
            Map<EncodeHintType, Object> hints = Maps.newHashMap();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            hints.put(EncodeHintType.MARGIN, 4);

            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.CODE_128, 100, 30, hints);
            BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            javax.imageio.ImageIO.write(bufferedImage, "png", byteArrayOutputStream);

            return byteArrayOutputStream.toByteArray();
        }catch (Exception e){
            return null;
        }
    }

    @Override
    public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {


    }

    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        Workbook workbook = writeSheetHolder.getSheet().getWorkbook();
        Sheet sheet = workbook.getSheetAt(0);
        PrintSetup printSetup = sheet.getPrintSetup();
        printSetup.setPaperSize(PrintSetup.A4_PAPERSIZE); // 设置A4纸张
        //sheet.setAutobreaks(true); // 关闭自动分页
        //sheet.setFitToPage(true); // 设置适合一页打印
        //writeSheetHolder.getSheet().setFitToPage(true);
        //writeSheetHolder.getSheet().setAutobreaks(true);
       // workbook.removeSheetAt(1);
    }
}
